# encoding = utf-8
import pandas as pd

from application.logging import logger
from application.utils.CodeTimingUtil import CodeTimingUtil
from application.utils.MySQLUtils import MySQLUtils


@CodeTimingUtil(name="查询室内温度数据[connect_mysql_read_inside_temperature_data]")
def func_read_inside_temperature_data(station_id):
    """
    查询室内温度数据
    :param station_id:
    :return:
    """
    #
    # 转换类型
    station_id = str(station_id)
    logger.info(f"换热站编号: {station_id}")

    # 查询语句:limit=10000
    sql = f"SELECT station_id, collect_time, room_id, room_temp " \
          f"FROM sn_control_model_room_temp " \
          f"WHERE station_id= '{station_id}' " \
          f"limit 1000000"  # TODO 数据量太大，
    # sql = f"SELECT * FROM sn_control_model_room_temp WHERE station_id= '{station_id}' limit 10000"
    logger.info(f"查询语句[室内温度][ALL]: {sql}")

    # 获取连接
    con = MySQLUtils.get_mysql_connection()

    #
    # 查询数据
    timer = CodeTimingUtil.timer_start(name="查询室内温度[ALL]")
    df: pd.DataFrame = pd.read_sql_query(sql=sql, con=con)
    CodeTimingUtil.timer_stop(timer)
    logger.info(f"查询结果[室内温度]: \n {df}")

    #
    # 筛选数据:字段
    df = df[["station_id", "collect_time", "room_id", "room_temp"]]
    logger.info(f"筛选结果[室内温度]: \n {df}")

    #
    # 筛选数据:室内温度不能为空
    df = df[df["room_temp"] != "null"]
    logger.info(f"筛选结果[室内温度数据][df[df['room_temp'] != 'null']]: \n {df}")

    #
    # 室温字典:(KEY=采集时间-保留到小时，VAL=室温列表)
    dict_temperature = {}

    #
    # for ->
    for i, _ in enumerate(df["collect_time"]):
        # 截取数据:前13个字符,保留到小时
        Time = str(_)[:13]
        # print(Time)
        # 放入字典
        dict_temperature.setdefault(Time, []).append(df["room_temp"][i])
        pass  # <- for
    #
    #
    logger.info(f"室内温度数据[dict_temperature][len]: {len(dict_temperature)}")
    # logger.info(f"室内温度数据[dict_temperature][key]: {dict_temperature.keys()}")
    
    #
    # 返回数据
    return dict_temperature
    pass


if __name__ == '__main__':
    func_read_inside_temperature_data("1353374478217908224")
    pass
